<template>
  <view class="container">
    <!-- 消息列表区域 - 可滚动 -->
    <scroll-view 
      class="message-list" 
      scroll-y 
      :scroll-top="scrollTop"
      :scroll-into-view="scrollIntoView"
      scroll-with-animation
    >
      <view 
        v-for="(message, index) in messages" 
        :key="index"
        :id="'msg-' + index"
        class="message-item"
        :class="{'message-right': message.senderId === currentUserId}"
      >
        <view class="message-bubble">
          <view v-if="message.messageType === 'TEXT'" class="text-message">
            {{ message.content }}
          </view>
          <image 
            v-else-if="message.messageType === 'IMAGE'" 
            :src="message.imageUrl" 
            class="image-message"
            mode="aspectFit"
            @click="previewImage(message.imageUrl)"
          />
        </view>
      </view>
    </scroll-view>
    
    <!-- 输入区域 - 固定在底部 -->
    <view class="input-area">
      <view class="input-wrapper">
        <input 
          v-model="inputText" 
          class="input" 
          placeholder="输入消息..."
          @confirm="sendTextMessage"
        />
      </view>
      <view class="icon-btn" @click="chooseImage">
        <text>+</text>
      </view>
      <view class="send-btn" @click="sendTextMessage">
        <text>发送</text>
      </view>
    </view>
  </view>
</template>

<script>
import api from '../../utils/api.js'
import websocket from '../../utils/websocket.js'

export default {
  data() {
    return {
      currentUserId: '',
      otherUserId: '',
      otherUserName: '',
      messages: [],
      inputText: '',
      scrollTop: 0,
      scrollIntoView: '',
      socketTask: null
    }
  },
  onLoad(options) {
    this.currentUserId = options.userId || 'user1'
    this.otherUserId = options.otherUserId || 'user2'
    this.otherUserName = options.otherUserName || '对方'
    
    uni.setNavigationBarTitle({
      title: this.otherUserName
    })
    
    this.loadMessages()
    this.connectWebSocket()
  },
  onUnload() {
    if (this.socketTask) {
      websocket.close()
    }
  },
  methods: {
    async loadMessages() {
      try {
        const res = await api.getChatMessages(this.currentUserId, this.otherUserId)
        if (res.statusCode === 200) {
          this.messages = res.data || []
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      } catch (e) {
        console.error('加载消息失败', e)
      }
    },
    
    connectWebSocket() {
      this.socketTask = websocket.connect(
        this.currentUserId,
        (message) => {
          console.log('收到消息:', message)
          // 只显示对方发送的消息（自己发送的消息已经立即显示了）
          if (message.senderId === this.otherUserId) {
            this.messages.push({
              ...message,
              createdAt: message.createdAt ? new Date(message.createdAt) : new Date()
            })
            this.$nextTick(() => {
              this.scrollToBottom()
            })
          }
        },
        (error) => {
          console.error('WebSocket错误', error)
        }
      )
    },
    
    sendTextMessage() {
      if (!this.inputText.trim()) {
        return
      }
      
      const message = {
        senderId: this.currentUserId,
        receiverId: this.otherUserId,
        messageType: 'TEXT',
        content: this.inputText,
        createdAt: new Date().toISOString()
      }
      
      // 通过WebSocket发送消息
      websocket.send(message)
      
      // 立即显示在界面上
      this.messages.push({
        ...message,
        createdAt: new Date()
      })
      this.inputText = ''
      
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },
    
    chooseImage() {
      uni.chooseImage({
        count: 1,
        success: async (res) => {
          const filePath = res.tempFilePaths[0]
          uni.showLoading({ title: '上传中...' })
          
          try {
            const uploadRes = await api.uploadImage(filePath)
            const message = {
              senderId: this.currentUserId,
              receiverId: this.otherUserId,
              messageType: 'IMAGE',
              imageUrl: uploadRes.url,
              content: '[图片]',
              createdAt: new Date().toISOString()
            }
            
            // 通过WebSocket发送消息
            websocket.send(message)
            
            // 立即显示在界面上
            this.messages.push({
              ...message,
              createdAt: new Date()
            })
            
            this.$nextTick(() => {
              this.scrollToBottom()
            })
            
            uni.hideLoading()
          } catch (e) {
            console.error('发送图片失败', e)
            uni.hideLoading()
            uni.showToast({
              title: '发送失败',
              icon: 'none'
            })
          }
        }
      })
    },
    
    previewImage(url) {
      uni.previewImage({
        urls: [url],
        current: url
      })
    },
    
    scrollToBottom() {
      const lastIndex = this.messages.length - 1
      if (lastIndex >= 0) {
        this.scrollIntoView = 'msg-' + lastIndex
      }
    }
  }
}
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #ededed;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.message-list {
  flex: 1;
  padding: 20rpx;
  padding-top: 100rpx;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  margin-bottom: 0;
  box-sizing: border-box;
}

.message-item {
  margin-bottom: 24rpx;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
}

.message-item:last-child {
  margin-bottom: 120rpx;
}

.message-right {
  flex-direction: row-reverse;
}

.message-bubble {
  max-width: 70%;
  display: inline-block;
}

.text-message {
  background-color: #ffffff;
  padding: 16rpx 24rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #000000;
  word-wrap: break-word;
}

.message-right .text-message {
  background-color: #95ec69;
}

.image-message {
  width: 300rpx;
  height: 300rpx;
  border-radius: 8rpx;
}

.input-area {
  background-color: #f7f7f7;
  border-top: 1rpx solid #d9d9d9;
  padding: 16rpx 20rpx;
  padding-bottom: 20rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-shrink: 0;
  box-sizing: border-box;
  position: relative;
  z-index: 10;
}

.input-wrapper {
  flex: 1;
  margin-right: 16rpx;
}

.input {
  width: 100%;
  height: 56rpx;
  background-color: #ffffff;
  border: 1rpx solid #d9d9d9;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.icon-btn {
  width: 56rpx;
  height: 56rpx;
  background-color: #ffffff;
  border: 1rpx solid #d9d9d9;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16rpx;
  flex-shrink: 0;
}

.icon-btn text {
  font-size: 36rpx;
  color: #000000;
  line-height: 56rpx;
}

.send-btn {
  width: 100rpx;
  height: 56rpx;
  background-color: #07c160;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.send-btn text {
  font-size: 26rpx;
  color: #ffffff;
}
</style>
